﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PersonaLibrary.Data.ServiceReference;
using PersonaLibrary.PersonaliiReference;

namespace PersonaLibrary.ViewModel.CheckDuplicatesViewModel
{
	internal class CheckDuplicatesViewModel : BaseViewModel
	{
		private RelayCommand _startCommand;
		private int _jobProgress;
		private bool _started;

		protected DataServiceContextWrapper Context = new DataServiceContextWrapper();

		public RelayCommand StartCommand
		{
			get
			{
				if(_startCommand == null)
					_startCommand = new RelayCommand(x => Start(), x => !_started);
				return _startCommand;
			}
		}

		public int JobProgress
		{
			get { return _jobProgress; }
		}

		public void Start()
		{
			_started = true;

			Task.Factory.StartNew(CheckJobs);

			Context.SaveChanges();
		}

		private void CheckJobs()
		{
			var selectedJobs = Context.TryCreateAndExecuteQuery<Job>(@"Job?$select=Name,Id", "Не удалось загрузить cписок должностей").ToList();

			List<string> keys = new List<string>();
			foreach (var job in selectedJobs)
			{
				if (keys.Contains(job.Name))
				{
					var selectedConnections = Context.TryCreateAndExecuteQuery<ConnectionJobEmplDep>(string.Format("ConnectionJobEmplDep?$filter=JobId eq {0}", job.Id),
						"Не удалось загрузить cписок должностей");

					if(selectedConnections.Count() == 0)
						Context.DeleteObject(job);
				}
				else
					keys.Add(job.Name);

				_jobProgress = (keys.Count/selectedJobs.Count) * 100;
				RisePropertyChanged("JobProgress");
			}

			Context.SaveChanges();
			_started = false;
		}
	}
}
